<template>
  <!-- 按钮点击，上传展示上传文件列 -->
  <upload-base ref="baseRef" v-model="fileList" v-bind="attrs" :prop="prop">
    <template #tip>
      <span class="ml10">{{ notice }}</span>
    </template>
  </upload-base>
  <ul class="file_list_show">
    <li v-for="(file, index) in fileList" :key="index">
      <img :src="getIcon(file)" />
      <span
        :class="file.link || file?.raw?.link ? 'link_cursor' : 'link_name'"
        @click="handleFileView(file)"
        >{{ file.name || file.raw.name }}</span
      >
      <span class="time_delete">
        <time>{{
          dateFormat(
            file.date || file?.raw?.date || file.lastModifiedDate || file?.raw?.lastModifiedDate
          )
        }}</time>
        <img :src="Delete" @click="handleRemove(index)" />
      </span>
    </li>
  </ul>
</template>
<script setup>
import { ElMessage } from 'element-plus';
import { dateFormat } from '@/utils/variables.js';
import UploadBase from './UploadBase.vue';
import { apiMethods } from '@/utils/http.js';

import IconPdf from '@/assets/image/Pdf.png';
import IconExcel from '@/assets/image/Excel.png';
import IconPhoto from '@/assets/image/Photo.png';
import IconFile from '@/assets/image/File.png';
import Delete from '@/assets/image/delete.png';

const props = defineProps({
  prop: {
    type: String,
    default: '',
  },
  modelValue: {
    type: Array,
    default: [],
  },
  notice: {
    type: String,
    default: '',
  },
  iconImg: {
    // 自定义图标
    type: String,
    default: '',
  },
  deleteConfig: {
    // 删除请求接口信息
    type: Object,
    default: () => {
      return {};
    },
  },
});
const emits = defineEmits(['update:modelValue', 'itemEvent']);

const imageFormat = ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'pct', 'raw', 'tga', 'tif', 'psd', 'webp'];

const baseRef = ref();

const attrs = useAttrs();

function getIcon(row) {
  let rowName = row?.name || row?.raw?.name;
  if (!rowName) return props.iconImg || IconFile;
  let url = IconFile;
  let fileSuffix = rowName.substring(rowName.lastIndexOf('.') + 1);
  fileSuffix = fileSuffix?.toLowerCase(); // 转小写匹配
  if (imageFormat.indexOf(fileSuffix) > -1) {
    url = IconPhoto;
    fileSuffix = 'image';
  } else if (fileSuffix === 'pdf') {
    url = IconPdf;
  } else if (fileSuffix === 'xls' || fileSuffix === 'xlsx') {
    url = IconExcel;
  }
  return props.iconImg || url;
}

const newValue = computed({
  get() {
    init(props.modelValue);
    return props.modelValue;
  },
  set(val) {
    emits('update:modelValue', val);
  },
});

let fileList = ref(newValue);

function init(files) {
  nextTick(() => {
    baseRef.value.init(files);
  });
}

// 删除列表中的附件
async function handleRemove(index) {
  const {
    requestApi = '',
    idKey = 'recid',
    axiosMethod = 'post',
    paramsArr = [],
  } = props.deleteConfig;
  let row = fileList.value[index];
  if (requestApi && row[idKey]) {
    let params = {};
    params[idKey] = row[idKey];
    if (paramsArr?.length) {
      paramsArr.forEach(item => {
        if (item.definiteValue) params[item.key] = item.definiteValue;
        if (item.value) params[item.key] = row[item.value];
      });
    }
    // 调删除接口
    try {
      let res = await apiMethods[axiosMethod](requestApi, params);
      if (res.data.code || res.data.errorCode === '200') {
        ElMessage.success(res.data.msg);
        fileList.value.splice(index, 1);
        baseRef.value.init(fileList.value);
      } else {
        ElMessage.error(res.data.msg);
      }
    } catch (error) {
      console.log(error, 'errr');
    }
  } else {
    fileList.value.splice(index, 1);
    baseRef.value.init(fileList.value);
  }
}

function handleFileView(file) {
  let url = file.link || file?.raw?.link;
  let name = file.name || file?.raw?.name;
  let uid = file.uid || file?.raw?.uid;
  let type = file?.type || file?.raw?.type || '';

  if (url) {
    // 列表或者详情接口有返回url地址
    let params = encodeURIComponent(
      JSON.stringify({
        url,
        name,
      })
    );
    let fileSuffix = name?.substring(name.lastIndexOf('.') + 1);
    fileSuffix = fileSuffix?.toLowerCase(); // 转小写匹配
    if (imageFormat.indexOf(fileSuffix) > -1) fileSuffix = 'image';
    emits('itemEvent', {
      ...attrs,
      ...file,
      fileParams: params,
      component: 'viewFile',
      fileSuffix,
    });
  } else {
    uid ? '' : ElMessage.warning('No attachment address found');
  }
}
</script>
<style lang="scss" scoped>
.ml10 {
  margin-left: 10px;
}
.file_list_show {
  margin-top: 10px;
  width: 100%;
  li {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    background: #f7f7f7;
    border-radius: 4px;
    padding: 0 16px 0 6px;
    margin-bottom: 10px;
    height: 32px;
    > img {
      width: 18px;
      height: 18px;
      margin-right: 10px;
    }
    .time_delete {
      margin-left: auto;
      time {
        margin-right: 30px;
      }
      img {
        position: relative;
        top: 4px;
        cursor: pointer;
      }
    }
  }
}
.link_cursor {
  cursor: pointer;
}
</style>
